package com.violet.service.manager.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.violet.domain.po.User;
import com.violet.domain.result.ResultPage;
import com.violet.domain.search.MyPage;
import com.violet.domain.search.manager.MUserSearch;
import com.violet.domain.vo.manager.MUserVo;
import com.violet.mapper.UserMapper;
import com.violet.service.manager.MUserService;
import com.violet.utils.SearchUtils;
import com.violet.utils.TransitionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Stream;

@Service
@RequiredArgsConstructor
public class MUserServiceImpl extends ServiceImpl<UserMapper, User>
        implements MUserService {

    private final TransitionUtils<?, User, MUserVo> transition;

    @Override
    public ResultPage<List<MUserVo>> search(MUserSearch search, MyPage myPage) {
        Page<User> page = new Page<>(myPage.getCurrentPage(), myPage.getPageSize());
        baseMapper.selectPage(page, SearchUtils.getSearchWrapper(search));
        Stream<MUserVo> stream = page.getRecords().stream().map(item -> transition.transition(item, MUserVo.class));
        return ResultPage.success(stream.toList(), "分页搜索", page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setStatus(String id, Boolean status) {
        User user = baseMapper.getByIdWithPessimisticLock(id);
        if (user == null) throw new RuntimeException("用户不存在");
        user.setStatus(status);
        return baseMapper.updateById(user) == 1;
    }

}
